using System;
using System.Collections.Generic;
using System.Net;

namespace RStein.Posterous.API
{
    internal class PosterousComment : EntityWithClientStateBase<PosterousComment>, IPosterousComment
    {
        #region private variables        
        #endregion private variables
        #region Constructors
        public PosterousComment(int? id) : base(id, PosterousEntityState.Loaded)
        {
            
            
        }
        
        public PosterousComment(IPosterousPost parentPost) : base(null, PosterousEntityState.New)
        {
            if (parentPost == null)
            {
                throw new ArgumentNullException("parentPost");
            }
            Author = PosterousAuthor.GetUnknownAuthor();
            Body = String.Empty;
            Post = parentPost;
            CreateDate = DateTime.Now;
            
        }
        #endregion Constructors
        
        #region properties
     
        #endregion properties
        

        #region Implementation of IPosterousComment
        
        public IAuthor Author 
        { 
          get; 
          set; 
        }
        public DateTime CreateDate
        {
            get;
            set; 
        }
        public string Body
        {
            get;
            set; 
        }

        public IPosterousPost Post
        {
            get; 
            set;
        }
        

        #endregion

        
        #region Implementation of IEntityWithClientState
      
        
        protected override void SaveUpdated()
        {
            return;
        }

        protected override void SaveNew()
        {

            var builder = SimpleWebFactory.Instance.Create<IPosterousRequestBuilder>(); ;
            builder.StartBuildWebRequest(GlobalConstants.URL_ADD_COMMENT_TO_POST);
                        
           ((PosterousSite) Post.Site).AddSiteAuthInfo(builder);
           builder.BuildFormData(GlobalConstants.SITE_REQ_POST_ID, Post.Id.ToString());
           builder.BuildFormData(GlobalConstants.SITE_REQ_COMMENT_BODY, Body);
           builder.BuildFormData(GlobalConstants.SITE_REQ_POST_CREATE_DATE, 
                                 CreateDate.ToString(GlobalConstants.DATETIME_GMT_FORMAT));

            processCreateCommentResult(builder);
        }

        private void processCreateCommentResult(IPosterousRequestBuilder builder)
        {
            WebResponse response = builder.GetResponse();
            var respBuilder = new PosterousResponseBuilder();             
            Dictionary<string, string> vals = respBuilder.ParseResponse(response, new SendCommentResponseParser().GetResults);
            Id = Int32.Parse(vals[GlobalConstants.XML_ID_ELEMENT.ToString()]);

        }

        #endregion
    }
}